package com.socket.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 为每个client创建一个线程，用来处理client的业务
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2018/4/13 15:35
 * <h3>Copyright</h3> Copyright (c)2018 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class ServerThread implements Runnable {
    /**当前要处理的Socket对象*/
    Socket s = null;
    // 读取客户端的数据
    BufferedReader br;
    private InputStream is;
    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {

        if (null != s) {
            try {
                is  = s.getInputStream();
                br = new BufferedReader(new InputStreamReader(is,"utf-8"));
                String content = null;
                // TODO Auto-generated method stub
                while(is.available() != 0 && (content = readFromClient()) != null) {
                    System.out.println(content);
                    //并把数据发给每个客户端
                    for(Socket s : MutiThreadServerSocket.socketList) {
                        try {
                            OutputStream os = s.getOutputStream();
                            os.write(content.getBytes("utf-8"));
                            os.flush();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }




    }


    /**
     * 读取客户端数据
     * @return
     */
    public String readFromClient () {
        if(null != br) {
            try {
                return br.readLine();
            } catch (IOException e) {
                //捕捉到异常，表明s 对应的客户端已经关闭
                MutiThreadServerSocket.socketList.remove(s);
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

}
